<?php

if (!defined('TOBBIVM'))
	header('location:/template/notrepassing.php');
/**
 * This file is part of TobbiVMShop.
 *
 * TobbiVMShop is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * TobbiVMShop is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with TobbiVMShop.  If not, see <http://www.gnu.org/licenses/>.
 */
/**
 * after successfull order-confirm / payed-order
 * save all order-data and show a thank-you-page
 * 
 * get: save.tpl.php
 * used from actually payment-function like xxxxx.payment.php
 *
 * @version    $Id$
 * @package    TobbiVM-Shop
 * @copyright  Copyright (C) 2012
 * @author     Norbert Gebert
 * @license    GPL3
 */
if (!isset($_SESSION['commentx']))
{
	header('location: index.php');
	exit;
}
$mysqlBuffer = array();
// 1. Step: save customer-data
$mysqlBuffer['orderer_order_date'] = date("Y-m-d H:i:s");
$mysqlBuffer['orderer_connection_data'] = "IP: " . $_SERVER['REMOTE_ADDR'] . "\n" .
	"Port: " . $_SERVER['REMOTE_PORT'] . "\n" .
	"Server-IP: " . $_SERVER['SERVER_ADDR'] . "\n" .
	"Browser: " . $_SERVER['HTTP_USER_AGENT'] . "\n";

if (!isset($_SESSION['ordernumberx']))
{
	db::getInstance()->where('config_key', 'ordernumber');
	$result = db::getInstance()->getOne('config');
	$_SESSION['ordernumberx'] = round($result['config_value']);
	unset($result);

	$data = Array('config_value' => $_SESSION['ordernumberx'] + 1);
	db::getInstance()->where('config_key', 'ordernumber');
	db::getInstance()->update('config', $data);
}
$mysqlBuffer['orderer_order_id'] = $_SESSION['ordernumberx'];
$mysqlBuffer['orderer_comment'] = $_SESSION['commentx'];
$mysqlBuffer['orderer_total'] = $_SESSION['orderpricex'];

$value = 0;
foreach ($_SESSION['ordertaxx'] as $val)
{
	$a = str_replace(',', '.', $val['value']);
	$value += floatval($a);
}

$mysqlBuffer['orderer_total_tax'] = $value;
$mysqlBuffer['orderer_shipping_id'] = $_SESSION['shippingidx'];
$mysqlBuffer['orderer_shipping_total'] = $_SESSION['shippingtotalx'];
$mysqlBuffer['orderer_payment_id'] = $_SESSION['paymentidx'];

db::getInstance()->where('orderer_id', $_SESSION['ordererIdx']);
db::getInstance()->update('orderer', $mysqlBuffer);

// 2. Save all order-products and values in table ordered
$a = 1;

foreach ($_SESSION['productListx'] as $order)
{
	$mysqlBuffer = array();
	db::getInstance()->where('product_id', $order['productId']);
	$row = db::getInstance()->getOne('product');

	$mysqlBuffer['order_id'] = $_SESSION['ordernumberx'];
	$mysqlBuffer['order_order'] = $a;
	$mysqlBuffer['order_product_id'] = $order['productId'];
	$mysqlBuffer['order_product_sku'] = $order['sku'];
	$mysqlBuffer['order_status'] = '0';

	$mysqlBuffer['order_mass_id'] = $row['product_mass_id'];
	$mysqlBuffer['order_product_quantity'] = $order['number'];
	$mysqlBuffer['order_product_name'] = $order['product'];
	$mysqlBuffer['order_item_price'] = floatval(str_replace(',', '.', $order['pricePerItem']));
	$mysqlBuffer['order_total_price'] = floatval(str_replace(',', '.', $order['priceTotal']));
	$mysqlBuffer['order_price_id'] = $row['product_price_id'];

	db::getInstance()->where('tax_id', $row['product_tax_id']);
	$buffer = db::getInstance()->getOne('tax');
	$mysqlBuffer['order_tax_value'] = $buffer['tax_value'];
	$buffer = NULL;

	$mysqlBuffer['order_tax_id'] = $row['product_tax_id'];
	$mysqlBuffer['order_attribute_string'] = $order['attribute'];

	db::getInstance()->insert('ordered', $mysqlBuffer);

// Update stocks/sales
	$data = Array(
	 'product_stocks_quantity' => ($row['product_stocks_quantity'] - $mysqlBuffer['order_product_quantity']),
	 'product_sales' => ($row['product_sales'] + $mysqlBuffer['order_product_quantity']));
	db::getInstance()->where('product_id', $order['productId']);
	db::getInstance()->update('product', $data);

	unset($mysqlBuffer);
	$a++;
}

// Create mailpages
$file = 'module/cart/cart.make.invoice.php';
if (is_file($file))
	include_once $file;
$cid = uniqid(time());
$invoice = makeInvoice($cid, TRUE);

date_default_timezone_set('Etc/UTC');
// Send mails
require 'module/class/email/PHPMailerAutoload.php';
//Create a new PHPMailer instance
$mail = new PHPMailer();
$mail->CharSet = 'utf-8';
$mail->SetLanguage(substr(LANGUAGE, 0, 2));
//Tell PHPMailer to use SMTP
$mail->isSMTP();
$mail->SMTPDebug = SMTP_DEBUG;
$mail->Debugoutput = 'html';
$mail->Host = MAIL_HOSTNAME;
$mail->Port = 25;
$mail->SMTPAuth = MAIL_AUTH;
$mail->Username = MAIL_USER;
$mail->Password = MAIL_PASSWORD;
$mail->setFrom(MAIL_SENDER, MAIL_SENDER_NAME);

db::getInstance()->where('orderer_id', $_SESSION['ordererIdx']);
$row = db::getInstance()->getOne('orderer');

//Set who the message is to be sent to
$mail->addAddress($row['orderer_email'],
	($row['orderer_firstname'] . ' ' .
	$row['orderer_lastname']));
$row = NULL;
$mail->Subject = _('Your invoice for order at') . ' ' . MAIL_ORDER_NAME;
$mail->AddEmbeddedImage('template/images/logoemail.jpg', $cid, 'logo.jpg', 'base64',
	'image/jpeg');
$mail->msgHTML($invoice);
$mail->send();

// Send copy to shop
//Create a new PHPMailer instance
$mail = new PHPMailer();
$mail->CharSet = 'utf-8';
$mail->Priority = 1;
$mail->SetLanguage(substr(LANGUAGE, 0, 2));
//Tell PHPMailer to use SMTP
$mail->isSMTP();
$mail->SMTPDebug = SMTP_DEBUG;
$mail->Debugoutput = 'html';
$mail->Host = MAIL_HOSTNAME;
$mail->Port = 25;
$mail->SMTPAuth = MAIL_AUTH;
$mail->Username = MAIL_USER;
$mail->Password = MAIL_PASSWORD;
$mail->isHTML(true);

$invoice = makeInvoice($cid);
$mail->setFrom(MAIL_SENDER, MAIL_SENDER_NAME);
//Set who the message is to be sent to
$mail->addAddress(MAIL_ORDER, MAIL_ORDER_NAME);
$mail->Subject = _('An order has been received!');
//$mail->addAttachment('template/images/logoemail.jpg', 'logo.jpg');
$mail->AddEmbeddedImage('template/images/logoemail.jpg', $cid, 'logo.jpg', 'base64',
	'image/jpeg');
$mail->msgHTML($invoice);
//$mail->send();

foreach ($_SESSION['productListx'] as $order)
{
	$refCart->delete($order['productId']);
}
unset($_SESSION["cartIdx"]);
unset($_SESSION["lastPagex"]);
unset($_SESSION["currentPagex"]);
unset($_SESSION["ordererIdx"]);
unset($_SESSION["productListx"]);
unset($_SESSION["commentx"]);
unset($_SESSION["ordershippingx"]);
unset($_SESSION["shippingidx"]);
unset($_SESSION["shippingtotalx"]);
unset($_SESSION["totalpricex"]);
unset($_SESSION["orderpricex"]);
unset($_SESSION["ordertaxx"]);
unset($_SESSION["paymentx"]);
unset($_SESSION["paymentidx"]);
unset($_SESSION["ordernumberx"]);

if (!$mail->send())
{ // Could not mail send
	message::setErrorRow(_('Unfortunately, during the order process, an error has occurred.'),
		TRUE);
	message::setErrorRow(_('Please notify Shop@TobbiVM.de it. Sorry for the inconvenience.'),
		FALSE);

	$data = Array('error_text' => '<b>' . _('An error occurred while sending an order!') . '</b><br><hr>' . $invoice,
	 'error_date' => date("Y-m-d H:i:s"),
	 'error_done' => 0);
	db::getInstance()->insert('error', $data);

	// Purchase completion page
	db::getInstance()->where('page_name', 'sorry');
	$result = db::getInstance()->getOne('page');

	$refPage->assign('header', $result['page_header']);
	$refPage->assign('text', $result['page_text']);

	unset($result);
	$refPage->addtpl('content', '/' . $page . '/sorry.tpl.php');
}
else
{ // Mail send ok
	message::setNoteRow(_('Thank you for your order.'), TRUE);

	// Purchase completion page
	db::getInstance()->where('page_name', 'thanks');
	$result = db::getInstance()->getOne('page');

	$refPage->assign('header', $result['page_header']);
	$refPage->assign('text', $result['page_text']);
	unset($result);
	$refPage->addtpl('content', '/' . $page . '/thanks.tpl.php');
}
?>